/**
 * 主题切换工具
 */

/**
 * 主题类型定义
 */
export type ThemeType = 'light' | 'dark' | 'auto';

/**
 * 主题配置接口
 */
export interface ThemeConfig {
  name: string;
  type: ThemeType;
  colors: {
    primary: string;
    secondary: string;
    success: string;
    warning: string;
    danger: string;
    info: string;
    background: string;
    surface: string;
    text: string;
    textSecondary: string;
    border: string;
    shadow: string;
  };
  variables?: Record<string, string>;
}

/**
 * 预设主题配置
 */
export const defaultThemes: Record<string, ThemeConfig> = {
  light: {
    name: '浅色主题',
    type: 'light',
    colors: {
      primary: '#409eff',
      secondary: '#909399',
      success: '#67c23a',
      warning: '#e6a23c',
      danger: '#f56c6c',
      info: '#909399',
      background: '#ffffff',
      surface: '#f5f7fa',
      text: '#303133',
      textSecondary: '#606266',
      border: '#dcdfe6',
      shadow: 'rgba(0, 0, 0, 0.1)'
    }
  },
  dark: {
    name: '深色主题',
    type: 'dark',
    colors: {
      primary: '#409eff',
      secondary: '#909399',
      success: '#67c23a',
      warning: '#e6a23c',
      danger: '#f56c6c',
      info: '#909399',
      background: '#1a1a1a',
      surface: '#2d2d2d',
      text: '#e4e7ed',
      textSecondary: '#c0c4cc',
      border: '#4c4d4f',
      shadow: 'rgba(0, 0, 0, 0.3)'
    }
  }
};

/**
 * 主题管理器类
 */
export class ThemeManager {
  private currentTheme: ThemeConfig;
  private customThemes: Map<string, ThemeConfig> = new Map();
  private listeners: Set<(theme: ThemeConfig) => void> = new Set();
  private mediaQuery: MediaQueryList | null = null;

  constructor(initialTheme?: ThemeConfig) {
    this.currentTheme = initialTheme || defaultThemes.light;
    this.init();
  }

  /**
   * 初始化主题管理器
   */
  private init(): void {
    // 从本地存储恢复主题
    const savedTheme = this.loadThemeFromStorage();
    if (savedTheme) {
      this.currentTheme = savedTheme;
    }

    // 监听系统主题变化
    this.initMediaQuery();

    // 应用主题
    this.applyTheme(this.currentTheme);
  }

  /**
   * 初始化媒体查询监听
   */
  private initMediaQuery(): void {
    if (typeof window !== 'undefined' && window.matchMedia) {
      this.mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
      this.mediaQuery.addEventListener('change', this.handleSystemThemeChange.bind(this));
    }
  }

  /**
   * 处理系统主题变化
   */
  private handleSystemThemeChange(): void {
    if (this.currentTheme.type === 'auto') {
      this.applyAutoTheme();
    }
  }

  /**
   * 应用自动主题
   */
  private applyAutoTheme(): void {
    const isDark = this.mediaQuery?.matches || false;
    const theme = isDark ? defaultThemes.dark : defaultThemes.light;
    this.applyTheme(theme);
  }

  /**
   * 设置主题
   */
  setTheme(theme: ThemeConfig | string): void {
    let themeConfig: ThemeConfig;

    if (typeof theme === 'string') {
      if (theme === 'auto') {
        themeConfig = { ...defaultThemes.light, type: 'auto' };
      } else {
        themeConfig = this.customThemes.get(theme) || defaultThemes[theme] || defaultThemes.light;
      }
    } else {
      themeConfig = theme;
    }

    this.currentTheme = themeConfig;
    this.saveThemeToStorage(themeConfig);
    this.applyTheme(themeConfig);
    this.notifyListeners(themeConfig);
  }

  /**
   * 获取当前主题
   */
  getCurrentTheme(): ThemeConfig {
    return this.currentTheme;
  }

  /**
   * 获取主题类型
   */
  getThemeType(): ThemeType {
    return this.currentTheme.type;
  }

  /**
   * 添加自定义主题
   */
  addCustomTheme(name: string, theme: ThemeConfig): void {
    this.customThemes.set(name, theme);
  }

  /**
   * 移除自定义主题
   */
  removeCustomTheme(name: string): void {
    this.customThemes.delete(name);
  }

  /**
   * 获取所有可用主题
   */
  getAvailableThemes(): Record<string, ThemeConfig> {
    return {
      ...defaultThemes,
      ...Object.fromEntries(this.customThemes)
    };
  }

  /**
   * 订阅主题变化
   */
  subscribe(listener: (theme: ThemeConfig) => void): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }

  /**
   * 应用主题
   */
  private applyTheme(theme: ThemeConfig): void {
    if (theme.type === 'auto') {
      this.applyAutoTheme();
      return;
    }

    const root = document.documentElement;
    const colors = theme.colors;

    // 应用颜色变量
    Object.entries(colors).forEach(([key, value]) => {
      root.style.setProperty(`--el-color-${key}`, value);
      root.style.setProperty(`--theme-color-${key}`, value);
    });

    // 应用自定义变量
    if (theme.variables) {
      Object.entries(theme.variables).forEach(([key, value]) => {
        root.style.setProperty(`--theme-${key}`, value);
      });
    }

    // 设置主题类名
    root.className = root.className.replace(/theme-\w+/g, '');
    root.classList.add(`theme-${theme.type}`);

    // 设置meta标签
    this.updateMetaThemeColor(colors.primary);
  }

  /**
   * 更新meta主题色
   */
  private updateMetaThemeColor(color: string): void {
    let metaThemeColor = document.querySelector('meta[name="theme-color"]');
    if (!metaThemeColor) {
      metaThemeColor = document.createElement('meta');
      metaThemeColor.setAttribute('name', 'theme-color');
      document.head.appendChild(metaThemeColor);
    }
    metaThemeColor.setAttribute('content', color);
  }

  /**
   * 通知监听器
   */
  private notifyListeners(theme: ThemeConfig): void {
    this.listeners.forEach(listener => {
      try {
        listener(theme);
      } catch (error) {
        console.error('主题变化监听器执行失败:', error);
      }
    });
  }

  /**
   * 保存主题到本地存储
   */
  private saveThemeToStorage(theme: ThemeConfig): void {
    try {
      localStorage.setItem('theme-config', JSON.stringify(theme));
    } catch (error) {
      console.error('保存主题配置失败:', error);
    }
  }

  /**
   * 从本地存储加载主题
   */
  private loadThemeFromStorage(): ThemeConfig | null {
    try {
      const saved = localStorage.getItem('theme-config');
      return saved ? JSON.parse(saved) : null;
    } catch (error) {
      console.error('加载主题配置失败:', error);
      return null;
    }
  }

  /**
   * 销毁主题管理器
   */
  destroy(): void {
    if (this.mediaQuery) {
      this.mediaQuery.removeEventListener('change', this.handleSystemThemeChange.bind(this));
    }
    this.listeners.clear();
  }
}

/**
 * 全局主题管理器实例
 */
export const themeManager = new ThemeManager();

/**
 * 主题切换组合式函数
 */
export function useTheme() {
  /**
   * 设置主题
   */
  const setTheme = (theme: ThemeConfig | string) => {
    themeManager.setTheme(theme);
  };

  /**
   * 获取当前主题
   */
  const getCurrentTheme = () => {
    return themeManager.getCurrentTheme();
  };

  /**
   * 获取主题类型
   */
  const getThemeType = () => {
    return themeManager.getThemeType();
  };

  /**
   * 切换主题
   */
  const toggleTheme = () => {
    const currentType = getThemeType();
    if (currentType === 'light') {
      setTheme('dark');
    } else if (currentType === 'dark') {
      setTheme('light');
    } else {
      setTheme('light');
    }
  };

  /**
   * 订阅主题变化
   */
  const subscribe = (listener: (theme: ThemeConfig) => void) => {
    return themeManager.subscribe(listener);
  };

  return {
    setTheme,
    getCurrentTheme,
    getThemeType,
    toggleTheme,
    subscribe
  };
}

/**
 * 主题工具函数
 */
export const themeUtils = {
  /**
   * 设置主题
   */
  setTheme: (theme: ThemeConfig | string) => themeManager.setTheme(theme),

  /**
   * 获取当前主题
   */
  getCurrentTheme: () => themeManager.getCurrentTheme(),

  /**
   * 获取主题类型
   */
  getThemeType: () => themeManager.getThemeType(),

  /**
   * 切换主题
   */
  toggleTheme: () => {
    const currentType = themeManager.getThemeType();
    if (currentType === 'light') {
      themeManager.setTheme('dark');
    } else if (currentType === 'dark') {
      themeManager.setTheme('light');
    } else {
      themeManager.setTheme('light');
    }
  },

  /**
   * 添加自定义主题
   */
  addCustomTheme: (name: string, theme: ThemeConfig) => themeManager.addCustomTheme(name, theme),

  /**
   * 移除自定义主题
   */
  removeCustomTheme: (name: string) => themeManager.removeCustomTheme(name),

  /**
   * 获取所有可用主题
   */
  getAvailableThemes: () => themeManager.getAvailableThemes(),

  /**
   * 订阅主题变化
   */
  subscribe: (listener: (theme: ThemeConfig) => void) => themeManager.subscribe(listener),

  /**
   * 检查是否为深色主题
   */
  isDark: () => {
    const theme = themeManager.getCurrentTheme();
    if (theme.type === 'auto') {
      return window.matchMedia('(prefers-color-scheme: dark)').matches;
    }
    return theme.type === 'dark';
  },

  /**
   * 检查是否为浅色主题
   */
  isLight: () => {
    const theme = themeManager.getCurrentTheme();
    if (theme.type === 'auto') {
      return !window.matchMedia('(prefers-color-scheme: dark)').matches;
    }
    return theme.type === 'light';
  },

  /**
   * 获取主题色
   */
  getThemeColor: (colorName: keyof ThemeConfig['colors']) => {
    return themeManager.getCurrentTheme().colors[colorName];
  },

  /**
   * 创建主题配置
   */
  createTheme: (name: string, colors: Partial<ThemeConfig['colors']>, type: ThemeType = 'light'): ThemeConfig => {
    const baseTheme = type === 'dark' ? defaultThemes.dark : defaultThemes.light;
    return {
      name,
      type,
      colors: {
        ...baseTheme.colors,
        ...colors
      }
    };
  }
};

/**
 * CSS变量生成器
 */
export const generateCSSVariables = (theme: ThemeConfig): string => {
  const variables: string[] = [];
  
  Object.entries(theme.colors).forEach(([key, value]) => {
    variables.push(`--el-color-${key}: ${value};`);
    variables.push(`--theme-color-${key}: ${value};`);
  });

  if (theme.variables) {
    Object.entries(theme.variables).forEach(([key, value]) => {
      variables.push(`--theme-${key}: ${value};`);
    });
  }

  return variables.join('\n');
};

/**
 * 主题样式生成器
 */
export const generateThemeStyles = (theme: ThemeConfig): string => {
  const cssVariables = generateCSSVariables(theme);
  
  return `
    .theme-${theme.type} {
      ${cssVariables}
    }
  `;
};
